﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Maticsoft.DAL;
using System.Reflection;
using System.IO;

namespace BuildingForm.PersonInfo
{
    public partial class PersonSalary : Form 
    {
        public PersonSalary()
        {
            InitializeComponent();
            Init();
            //bind();
        }

        private void Init()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            //表头加粗，居中
            foreach (DataGridViewColumn col in this.dataGridView1.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("SimSun", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.dataGridView1.AllowUserToAddRows = false;
            //班组
            Maticsoft.DAL.Banz_Info info = new Banz_Info();
            DataTable dt = info.GetList("").Tables[0];
            List<string> strList = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strList.Add(dt.Rows[i]["bzmc"].ToString().Trim());
            }
            List<string> list = new List<string>();
            list.Add("全部");
            list.AddRange(strList);
            this.cboTeam.DataSource = list;
            //年，月,日
            int[] months = new int[12] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
            this.cboMonth.DataSource = months;
            this.cboMonth.Text = DateTime.Now.Month.ToString();
            int year = DateTime.Now.Year;
            int[] years = new int[12] { year - 11, year - 10, year - 9, year - 8, year - 7, year - 6, year - 5, year - 4, year - 3, year - 2, year - 1, year };
            this.cboYear.DataSource = years;
            this.cboYear.Text = DateTime.Now.Year.ToString();
            LoadDays();
            this.cboDay.Text = "25";
        }
        public decimal TotalHours = 0;
        private List<Salary> bind()
        {
            TotalHours = 0;
            Maticsoft.DAL.Kqjl_Info info = new Kqjl_Info();
            string sql = string.Empty;
            int year = Convert.ToInt32(this.cboYear.Text.ToString());
            int month = Convert.ToInt32(this.cboMonth.Text.ToString());
            int day = Convert.ToInt32(this.cboDay.Text.ToString());
            string strT = year + "/" + month + "/" + day;
            DateTime endT = Convert.ToDateTime(strT).AddDays(1).AddMilliseconds(-1);
            DateTime beginT = Convert.ToDateTime(strT).AddDays(1).AddMonths (-1).AddMilliseconds(1);

            sql = "CONVERT(varchar(10),a.kqsj,120)<='" + endT.ToString("yyyy-MM-dd") + "' and CONVERT(varchar(10),a.kqsj,120)>='" + beginT.ToString("yyyy-MM-dd") + "'";
            string team = this.cboTeam.Text.ToString().Trim();
            if (team != "全部")
            {
                sql += " and c.bzmc='" + team + "'";
            }
            sql += " order by a.sfzh,a.kqsj";
            DataTable dt = info.GetList4(sql).Tables[0];
            List<WorkTime> list = new List<WorkTime>();
            string sfzh_b = string.Empty;
            string dksj_b = string.Empty;
            DateTime beginTime = DateTime.MinValue;
            DateTime endTime = DateTime.MinValue;
            WorkTime arg = new WorkTime();
            int num = 1;
            decimal worktime = 0;
            //true进 false出
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string sfzh_1 = dr["sfzh"].ToString();
                string dksj_1 = dr["dksj"].ToString();
                //if (sfzh_1 != "0566805022") continue;
                if (sfzh_b.Equals(sfzh_1) && dksj_b.Equals(dksj_1))
                {
                    bool isEnter = Convert.ToBoolean(dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }
                    else
                    {
                        if (endTime == DateTime.MinValue && beginTime != DateTime.MinValue)
                        {
                            endTime = Convert.ToDateTime(dr["kqsj"]);
                            TimeSpan ts = endTime - beginTime;
                            decimal di = ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
                            worktime += di;
                            //防止一个人一天的再次
                            beginTime = DateTime.MinValue;
                            endTime = DateTime.MinValue;
                        }
                    }

                }
                else
                {
                    if (i != 0)
                    {
                        //工时大于0的才记录,不能用worktime，几秒时就是0
                        decimal gs = Math.Round(worktime / 3600, 2);
                        if (gs > 0)
                        {
                            arg.gs = Math.Round(worktime / 3600, 2);
                            worktime = 0;
                            list.Add(arg);
                            TotalHours += gs;
                            num++;
                        }
                    }
                    //防止下一天或一个人的再次
                    beginTime = DateTime.MinValue;
                    endTime = DateTime.MinValue;
                    bool isEnter = Convert.ToBoolean(dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }

                    sfzh_b = sfzh_1;
                    dksj_b = dksj_1;
                    WorkTime w = new WorkTime();
                    w.xh = num;
                    w.xm = dr["xm"].ToString();
                    w.xb = dr["xb"].ToString();
                    w.gh = dr["gh"].ToString();
                    w.sfzh = dr["sfzh"].ToString();
                    w.bz = dr["bzmc"].ToString();
                    w.gz = dr["gz"].ToString();
                    w.bankName = dr["BankName"] == null ? "" : dr["BankName"].ToString();
                    w.bankCard = dr["BankCard"] == null ? "" : dr["BankCard"].ToString();
                    w.rq = Convert.ToDateTime(dksj_b);
                    arg = w;
                }
            }
            if (!string.IsNullOrEmpty(arg.sfzh))
            {
                arg.gs = Math.Round(worktime / 3600, 2);
                list.Add(arg);
            }
            List<Salary> mList = ConvertSalary(list);
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = mList;
            return mList;
        }

      

        private void button1_Click(object sender, EventArgs e)
        {
           bind();
        }

        public static DataSet ToDataSet(IList p_List)
        {
            DataSet result = new DataSet();
            DataTable _DataTable = new DataTable();
            if (p_List.Count > 0)
            {
                PropertyInfo[] propertys = p_List[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    _DataTable.Columns.Add(pi.Name, pi.PropertyType);//columnName Type
                }

                for (int i = 0; i < p_List.Count; i++)
                {
                    ArrayList tempList = new ArrayList();    //一行数据的数组
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(p_List[i], null);//p_List[i]是集合中的某一个对象，GetValue 返回其属性值
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true); //LoadDataRow 查找和更新特定行。 如果找不到任何匹配行，则使用给定值创建新行
                }
            }
            result.Tables.Add(_DataTable);
            return result;
        }


        private void btnExport_Click(object sender, EventArgs e)
        {

            try
            {
                List<Salary> list = bind();
                if (list.Count == 0)
                {
                    MessageBox.Show("没有数据！"); return;
                }
                Sys_Info dao = new Sys_Info();
                string name = string.Empty;
                DataTable dtt = dao.GetList("").Tables[0];
                if (dtt.Rows.Count > 0)
                {
                    name = dtt.Rows[0]["gcmc"].ToString();
                }
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //设置文件类型   
                saveFileDialog1.Filter = " xls files(*.xls)|*.xls";
                //设置默认文件类型显示顺序   
                saveFileDialog1.FilterIndex = 2;
                //保存对话框是否记忆上次打开的目录   
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.FileName = "劳务人员工资表" + DateTime.Now.ToString("yyyyMMdd");
                //点了保存按钮进入   
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string team = this.cboTeam.Text.ToString().Trim();
                    if (team == "全部")
                    {
                        team = "所有人员";
                    }
                    team = team + "," + this.cboYear.Text.ToString() + "," + this.cboMonth.Text.ToString() + "," + name;
                    string fileName = saveFileDialog1.FileName;
                    string[] oldCols = new string[] { "xh",  "xm", "xb","bz","gz","aa","sfzh", "bank","cqts","xtgs","aa","aa","aa","aa","aa","aa","aa","aa"};
                    string[] newCols = new string[] { "编号", "姓名", "性别","班组","工种", "计件单位（日工资）", "身份证号", "银行（工资）卡开户行及卡号", "出勤工日", "考勤工时", "本月结算工资","累计结算工资","本月发放工资（借支）","累计发放工资","本月未发工资","累计未发工资","领款人签字确认","备注"};
                    DataTable dt = ToDataSet(list).Tables[0];
                    ExcelHelper.ExportByPersonSalary(dt, "劳务人员工资表", fileName, "Sheet1", oldCols, newCols, team);
                    MessageBox.Show("导出文件成功！"); return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出文件故障！"); return;
            }
        }

        public List<Salary> ConvertSalary(List<WorkTime> list)
        {
            if (list.Count == 0)
            {
                return null;
            }
            List<Salary> mList = new List<Salary>();
            Salary obj = new Salary();
            obj.sfzh = "";
            int k = 1;
            decimal dayGS = 0m;
            int dayNum = 0;
            for (var i = 0; i < list.Count; i++)
            {
                if (obj.sfzh != list[i].sfzh)
                {
                    if (obj.sfzh != "")
                    {
                        obj.xtgs = dayGS;
                        obj.cqts = dayNum;
                        dayGS = 0m;
                        dayNum = 0;
                        mList.Add(obj);
                        k++;
                    }
                    obj = new Salary();
                    obj.bz = list[i].bz;
                    obj.gz = list[i].gz;
                    obj.gh = list[i].gh;
                    obj.sfzh = list[i].sfzh;
                    obj.xb = list[i].xb;
                    obj.xm = list[i].xm;
                    obj.bank = list[i].bankName + "  " + list[i].bankCard;
                    obj.xh = k;
                }
                int num = list[i].rq.Day;
                dayGS += list[i].gs;
                dayNum++;
            }
            obj.xtgs = dayGS;
            obj.cqts = dayNum;
            mList.Add(obj);
            return mList;
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDays();
        }

        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDays();
        }
        public void LoadDays()
        {
            if (!String.IsNullOrEmpty(this.cboYear.Text) && !String.IsNullOrEmpty(this.cboMonth.Text))
            {
                int yearNum = Convert.ToInt32(this.cboYear.Text);
                int monthNum = Convert.ToInt32(this.cboMonth.Text);
                int days = DateTime.DaysInMonth(yearNum, monthNum);
                List<int> dayList = new List<int>();
                for (var i = 1; i <= days; i++)
                {
                    dayList.Add(i);
                }
                this.cboDay.DataSource = dayList;
                //this.cboDay.Text = "25";
            }
        }

     
    }
    public class Salary
    {
        public int xh { get; set; }
        public string xm { get; set; }
        public string sfzh { get; set; }
        public string gh { get; set; }
        public string bz { get; set; }
        public string gz { get; set; }
        public string xb { get; set; }
        public string bank { get; set; }
        public int cqts { get; set; }
        public decimal xtgs { get; set; }
        public string aa { get; set; }

    }
}
